package com.zyao89.view.zweb.views;

import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.net.http.SslError;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

class WebAgentEx extends WebAgent {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x00201, "WebAgentEx");

    private FixedOnReceivedTitle mFixedOnReceivedTitle;

    void setFixedOnReceivedTitle(FixedOnReceivedTitle fixedOnReceivedTitle) {
        mFixedOnReceivedTitle = fixedOnReceivedTitle;
    }

    @Override
    public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
        // 定制网址加载行为 类比 shouldOverrideUrlLoading
        return super.isNeedLoadUrl(webView, request);
    }

    @Override
    public void onLoadingPage(WebView webView, String url, PixelMap icon) {
        // 页面开始加载时自定义处理
        if (mFixedOnReceivedTitle != null) {
            mFixedOnReceivedTitle.onPageStarted();
        }
    }

    @Override
    public void onPageLoaded(WebView webView, String url) {
        // 页面加载结束后自定义处理
        if (mFixedOnReceivedTitle != null) {
            mFixedOnReceivedTitle.onPageFinished(webView);
        }
        super.onPageLoaded(webView, url);
    }

    @Override
    public void onLoadingContent(WebView webView, String url) {
        // 加载资源时自定义处理
        super.onLoadingContent(webView, url);
    }

    @Override
    public void onError(WebView webView, ResourceRequest request, ResourceError error) {
        // 发生错误时自定义处理
        super.onError(webView, request, error);
    }

    @Override
    public void onSslError(WebView webView, SslError error) {
        super.onSslError(webView, error);
    }

    @Override
    public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
        final String authority = "com.zyao89.view";
        final String rawFile = "/rawfile/";
        final String local = "/local/";
        Uri requestUri = request.getRequestUrl();
        if (authority.equals(requestUri.getDecodedAuthority())) {
            String path = requestUri.getDecodedPath();
            if (TextTool.isNullOrEmpty(path)) {
                return super.processResourceRequest(webView, request);
            }
            if (path.startsWith(rawFile)) {
                String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                try {
                    Resource resource = webView.getContext().getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                    ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                    return response;
                } catch (IOException e) {
                    HiLog.info(TAG, "open raw file failed");
                }
            }
            if (path.startsWith(local)) {
                // 根据自定义规则访问本地文件
                String localFile = webView.getContext().getFilesDir() + path.replace(local, "/");
                HiLog.info(TAG, "open local file " + localFile);
                File file = new File(localFile);
                if (!file.exists()) {
                    HiLog.info(TAG, "file not exists");
                    return super.processResourceRequest(webView, request);
                }
                String mimeType = URLConnection.guessContentTypeFromName(localFile);
                try {
                    InputStream inputStream = new FileInputStream(file);
                    ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                    return response;
                } catch (IOException e) {
                    HiLog.info(TAG, "open local file failed");
                }
            }
        }
        return super.processResourceRequest(webView, request);
    }
}
